<template>
	<button v-if="!hasUserProfileAPI" class="btn-get-phone" :style="[customStyle]" open-type="getUserInfo" @getuserinfo="handleGetUserInfo">
		<view v-if="$slots.default">
			<slot></slot>
		</view>
		<text v-else>{{text}}</text>
	</button>
	<button v-else class="btn-get-phone" :style="[customStyle]" @click="getUserProfile">
		<view v-if="$slots.default">
			<slot></slot>
		</view>
		<text v-else>{{text}}</text>
	</button>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		updateUserInfo
	} from "../../api/platform/user.js"
	
	export default {
		data() {
			return {
				wxCode: "",
				hasUserProfileAPI: false
			};
		},
		props: {
			customStyle: {
				type: Object,
				default: () => {
					return {};
				}
			},
			text: {
				type: String,
				default: "获取微信昵称"
			}
		},
		computed: {
			...mapState(["userInfo"])
		},
		mounted() {
			this.refreshWxCode();
			if (wx.getUserProfile) {
				this.hasUserProfileAPI = true
			}
		},
		beforeDestroy() {
			this.clearTime();
		},
		methods: {
			...mapMutations(['updateUserInfo', 'setWxLoginCode']),
			async getUserProfile() {
				if(wx.getUserProfile) {
					wx.getUserProfile({
						desc: "用于完善会员资料",
						lang: "zh_CN",
						success: async (res) => {
							let data = {
								code: this.wxCode,
								wxUserInfo: {
									encryptedData: res.encryptedData,
									iv: res.iv
								}
							}
							this.$emit('change', data)
						},
						fail: (err) => {
							this.$toast(err)
						}
					})
				} else {
					this.$toast("请升级微信为最新版")
				}
			},
			async handleGetUserInfo(res) {
				if (!res.detail.encryptedData) {
					return;
				}
				if (!this.wxCode) {
					uni.showToast({
						icon: "none",
						title: "登陆凭证失效了，请刷新页面"
					})
					return;
				}
				let data = {
					code: this.wxCode,
					wxUserInfo: {
						encryptedData: res.detail.encryptedData,
						iv: res.detail.iv
					}
				}
				this.$emit('change', data)
			},
			refreshWxCode() {
				//#ifndef H5
				this.$log("刷新微信登陆code");
				this.clearTime();
				uni.login({
					success: (res) => {
						this.wxCode = res.code;
						this.setWxLoginCode(res.code)
						this.$log("微信登陆code", this.wxCode);
						//5分钟刷新一次
						this.timeId = setInterval(() => {
							this.refreshWxCode();
						}, 5 * 60 * 1000)
					},
					fail: (err) => {
						this.$log("微信登陆code刷新失败", err);
					}
				})
				//#endif
			},
			clearTime() {
				if (this.timeId) {
					clearInterval(this.timeId);
					this.timeId = null;
				}
			},
		}
	}
</script>

<style scoped>
	.btn-get-phone {
		height: auto;
		background-color: rgba(255, 255, 255, 0);
		padding: 0;
		font-size: 28rpx;
	}

	.btn-get-phone:after {
		display: none;
	}
</style>

								})